﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Management;
using System.Windows.Forms;


namespace WindowsFormsApplication1
{
    class ProcessSensor : Sensor
    {
        private ManagementScope scope;
        private Process[] procList;
        private List<string> procListString;
        private ManagementEventWatcher ProcessStart;
        private WqlEventQuery ProcessStartQuery;
        private ManagementEventWatcher ProcessEnd;
        private WqlEventQuery ProcessEndQuery;
        public ProcessSensor()
        {
            procListString = new List<string>();

            name = "Process Sensor";
            scope = new ManagementScope("root\\CIMV2");
            ProcessStart = null;
            ProcessStartQuery = new WqlEventQuery();
            ProcessEnd = null;
            ProcessEndQuery = new WqlEventQuery();
            initialize_queries();
            ProcessStart.Start();
            ProcessEnd.Start();
            populate();
        }
        private void populate()
        {
            //data = System.Diagnostics.Process.GetProcesses(Environment.MachineName);
            //data = "process event detected";
            procList = System.Diagnostics.Process.GetProcesses(Environment.MachineName);
            foreach (Process p in procList)
                procListString.Add(p.ProcessName);
            data = procListString;
        }
        public void ProcessEventArrived(object sender, EventArrivedEventArgs e)
        {
            //MessageBox.Show("event arrived");
            populate();
            data = procListString;
            Notify();
        }
        private void initialize_queries()
        {
            ProcessStartQuery.EventClassName = "__InstanceCreationEvent";
            ProcessStartQuery.WithinInterval = new TimeSpan(0, 0, 10);
            ProcessStartQuery.Condition = @"TargetInstance ISA 'Win32_Process'";

            ProcessEndQuery.EventClassName = "__InstanceDeletionEvent";
            ProcessEndQuery.WithinInterval = new TimeSpan(0, 0, 10);
            ProcessEndQuery.Condition = @"TargetInstance ISA 'Win32_Process'";

            ProcessStart = new ManagementEventWatcher(scope, ProcessStartQuery);
            ProcessStart.EventArrived += new EventArrivedEventHandler(ProcessEventArrived);

            ProcessEnd = new ManagementEventWatcher(scope, ProcessEndQuery);
            ProcessEnd.EventArrived += new EventArrivedEventHandler(ProcessEventArrived);
        }
        /*public static bool isiTunesOpen()
        {
            foreach (Process p in procList)
            {
                if (p.ProcessName.ToString().Equals("iTunes"))
                    return true;
            }
            return false;
        }*/
    }
}
